package service

import (
	"context"

	"gitee.com/wangshh_123/cross-pay-go/src/database"
	"gitee.com/wangshh_123/cross-pay-go/src/models"
	"github.com/shopspring/decimal"
	"gorm.io/gorm"
)

// HlPayAccountBalanceService HlPay账户余额服务
type HlPayAccountBalanceService struct {
	db *gorm.DB
}

// NewHlPayAccountBalanceService 创建HlPay账户余额服务
func NewHlPayAccountBalanceService() *HlPayAccountBalanceService {
	return &HlPayAccountBalanceService{
		db: database.DB,
	}
}

// AccountBalanceInfo 账户余额信息
type AccountBalanceInfo struct {
	AccountNo               string  `json:"accountNo"`
	Currency                string  `json:"currency"`
	MemberID                string  `json:"memberId"`
	OriginalRealTimeBalance float64 `json:"originalRealTimeBalance"`
	OwnerNo                 string  `json:"ownerNo"`
	OwnerType               string  `json:"ownerType"`
	RealTimeBalance         float64 `json:"realTimeBalance"`
}

// AccountBalanceResponse 账户余额响应
type AccountBalanceResponse struct {
	Code                string               `json:"code"`
	Data                []AccountBalanceInfo `json:"data"`
	LocalBalance        float64              `json:"localBalance"`
	Msg                 string               `json:"msg"`
	Numbers             int                  `json:"numbers"`
	PageIndex           int64                `json:"pageIndex"`
	PageSize            int64                `json:"pageSize"`
	RoleID              int                  `json:"roleId"`
	Total               int64                `json:"total"`
	TotalTransferAmount float64              `json:"totalTransferAmount"`
}

// GetAccountBalancesByMatrixAccount 根据矩阵账户获取账户余额列表
func (s *HlPayAccountBalanceService) GetAccountBalancesByMatrixAccount(ctx context.Context, matrixAccount string, pageIndex, pageSize int64) (*AccountBalanceResponse, error) {
	// 查询账户余额列表
	var balances []models.HlPayAccountBalance
	offset := (pageIndex - 1) * pageSize

	query := s.db.Model(&models.HlPayAccountBalance{}).
		Where("owner_no = ? AND status = 'active'", matrixAccount)

	// 获取总数
	var total int64
	if err := query.Count(&total).Error; err != nil {
		return nil, err
	}

	// 分页查询
	if err := query.Offset(int(offset)).Limit(int(pageSize)).Find(&balances).Error; err != nil {
		return nil, err
	}

	// 转换数据格式
	balanceInfos := make([]AccountBalanceInfo, len(balances))
	var localBalance float64
	var totalTransferAmount float64

	for i, balance := range balances {
		realTimeBalance, _ := balance.RealTimeBalance.Float64()

		// 计算本地余额（USD余额）
		if balance.Currency == "USD" {
			localBalance = realTimeBalance
		}

		// 计算总转账金额（这里可以根据业务逻辑调整）
		totalTransferAmount += realTimeBalance

		balanceInfos[i] = AccountBalanceInfo{
			AccountNo:               balance.AccountNo,
			Currency:                balance.Currency,
			MemberID:                balance.MemberID,
			OriginalRealTimeBalance: realTimeBalance, // 这里可以根据需要设置原始余额
			OwnerNo:                 balance.OwnerNo,
			OwnerType:               balance.OwnerType,
			RealTimeBalance:         realTimeBalance,
		}
	}

	// 获取用户角色ID（这里可以根据业务逻辑调整）
	roleID := 3 // 默认角色ID

	return &AccountBalanceResponse{
		Code:                "0000",
		Data:                balanceInfos,
		LocalBalance:        localBalance,
		Msg:                 "succeed",
		Numbers:             len(balanceInfos),
		PageIndex:           pageIndex,
		PageSize:            pageSize,
		RoleID:              roleID,
		Total:               total,
		TotalTransferAmount: totalTransferAmount,
	}, nil
}

// GetAccountBalanceByAccountNo 根据账户号获取账户余额
func (s *HlPayAccountBalanceService) GetAccountBalanceByAccountNo(ctx context.Context, accountNo string) (*models.HlPayAccountBalance, error) {
	var balance models.HlPayAccountBalance
	err := s.db.Where("account_no = ? AND status = 'active'", accountNo).First(&balance).Error
	if err != nil {
		return nil, err
	}
	return &balance, nil
}

// UpdateAccountBalance 更新账户余额
func (s *HlPayAccountBalanceService) UpdateAccountBalance(ctx context.Context, accountNo string, newBalance decimal.Decimal) error {
	return s.db.Model(&models.HlPayAccountBalance{}).
		Where("account_no = ?", accountNo).
		Update("real_time_balance", newBalance).Error
}

// CreateAccountBalance 创建账户余额记录
func (s *HlPayAccountBalanceService) CreateAccountBalance(ctx context.Context, balance *models.HlPayAccountBalance) error {
	return s.db.Create(balance).Error
}

// GetTotalBalanceByMatrixAccount 根据矩阵账户获取总余额
func (s *HlPayAccountBalanceService) GetTotalBalanceByMatrixAccount(ctx context.Context, matrixAccount string) (decimal.Decimal, error) {
	var total decimal.Decimal
	err := s.db.Model(&models.HlPayAccountBalance{}).
		Select("COALESCE(SUM(real_time_balance), 0)").
		Where("owner_no = ? AND status = 'active'", matrixAccount).
		Scan(&total).Error
	return total, err
}

// GetAccountBalanceByOwnerNo 根据所有者编号获取账户余额
func (s *HlPayAccountBalanceService) GetAccountBalanceByOwnerNo(ownerNo string) (*models.HlPayAccountBalance, error) {
	var balance models.HlPayAccountBalance
	err := s.db.Where("owner_no = ? AND status = ?", ownerNo, "active").First(&balance).Error
	if err != nil {
		return nil, err
	}
	return &balance, nil
}

// SyncAccountBalanceFromHlPay 从hlpay同步账户余额
func (s *HlPayAccountBalanceService) SyncAccountBalanceFromHlPay(accountNo, currency, memberID, ownerNo string, realTimeBalance float64) error {
	// 检查是否已存在
	var existingBalance models.HlPayAccountBalance
	err := s.db.Where("account_no = ?", accountNo).First(&existingBalance).Error

	if err == gorm.ErrRecordNotFound {
		// 创建新记录
		balance := &models.HlPayAccountBalance{
			AccountNo:       accountNo,
			Currency:        currency,
			MemberID:        memberID,
			OwnerNo:         ownerNo,
			OwnerType:       "matrix",
			RealTimeBalance: decimal.NewFromFloat(realTimeBalance),
			Status:          "active",
		}
		return s.db.Create(balance).Error
	} else if err != nil {
		return err
	}

	// 更新现有记录
	return s.db.Model(&existingBalance).Update("real_time_balance", decimal.NewFromFloat(realTimeBalance)).Error
}

// DeleteAccountBalance 删除账户余额记录（软删除）
func (s *HlPayAccountBalanceService) DeleteAccountBalance(accountNo string) error {
	return s.db.Model(&models.HlPayAccountBalance{}).
		Where("account_no = ?", accountNo).
		Update("status", "inactive").Error
}
